import { mainRoutes } from '../../router/routes';

export const state = {
  // 菜单导航列表
  menus: [],
  // 菜单栏是否为收起状态
  isCollapse: false,
  // 当前路由
  currentRoute: null,
  // 历史路由列表
  historyRoutes: [],
};

export const mutations = {
  // 设置菜单导航列表
  SET_MENUS(state, menus) {
    state.menus = menus;
  },
  // 设置左侧导航是否展开或收起
  SET_COLLAPSE(state, payload) {
    state.isCollapse = payload;
  },

  // 当前路由
  SET_CURRENT_ROUTE(state, currentRoute) {
    state.currentRoute = currentRoute;
  },

  // 添加路由到历史路由列表中
  ADD_HISTORY_ROUTE(state, route) {
    state.historyRoutes.push(route);
  },

  // 删除历史路由列表中指定的路由
  REMOVE_HISTORY_ROUTE(state, path) {
    const routeIndex = state.historyRoutes.findIndex(d => d.path === path);
    if (routeIndex > -1) {
      state.historyRoutes.splice(routeIndex, 1);
    }
  },
};

export const getters = {};

export const actions = {
  setMenus({ commit }) {
    const menus = mainRoutes.reduce((curList, curItem, curIdx, oldList) => {
      const menu = {
        path: curItem.path,
        label: curItem.meta && curItem.meta.label,
        icon: curItem.meta && curItem.meta.icon,
      };
      if (curItem.children && curItem.children.length > 0) {
        menu.children = curItem.children.map(d => ({
          path: d.path,
          label: d.meta && d.meta.label,
          icon: d.meta && d.meta.icon,
        }));
      }
      curList.push(menu);
      return curList;
    }, []);
    commit('SET_MENUS', menus);
  },

  /**
   * 添加路由
   * @param commit
   * @param state
   * @param route 当前路由
   * @param limitCount  最大可缓存的路由 tab 数量
   */
  addHistoryRoute({ commit, state }, { route = null, limitCount }) {
    if (!route || state.historyRoutes.some(d => d.path === route.path)) {
      return;
    }
    const currentRouteLength = state.historyRoutes.length;
    // 如果传入缓存路由的限制数，则将列表中的第一个移除，新传入的往后追加
    if (limitCount > 1 && currentRouteLength > 1 && currentRouteLength > limitCount ) {
      commit('REMOVE_HISTORY_ROUTE', state.historyRoutes[0]);
    }
    commit('ADD_HISTORY_ROUTE', route);
  },

  /**
   * 删除路由
   * @param commit
   * @param route
   */
  removeHistoryRoute({ commit }, path) {
    commit('REMOVE_HISTORY_ROUTE', path);
  },
};
